package org.jeecg.exam;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class AliyunOssUtils {

    public static void main(String[] args) {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        // 这里替换为你的AccessKeyId和AccessKeySecret。
        String accessKeyId = "LTAI5tFmjrG5DcYZF9sZ2HdQ";
        String accessKeySecret = "QG8NHSCMdEMIhBdSm8caK5HPbhK6fa";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "shicao2";
        // 指定要扫描的本地目录路径，例如D:\\localpath\\exampledir。
        String directoryPath = "C:\\Users\\qing he\\Desktop\\12";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 获取目录路径对象
            Path baseDir = Paths.get(directoryPath);
            try (Stream<Path> paths = Files.walk(baseDir)) {
                paths.filter(Files::isRegularFile)
                     .forEach(file -> uploadFileToOss(ossClient, bucketName, baseDir, file));
            } catch (IOException e) {
                System.out.println("文件遍历失败：" + e.getMessage());
            }
        } catch (OSSException oe) {
            System.out.println("捕获到OSSException，这意味着您的请求到达了OSS，但由于某种原因被拒绝。");
            System.out.println("错误信息: " + oe.getErrorMessage());
            System.out.println("错误代码: " + oe.getErrorCode());
            System.out.println("请求ID: " + oe.getRequestId());
            System.out.println("主机ID: " + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("捕获到ClientException，这意味着客户端在试图与OSS通信时遇到了严重的内部问题，例如无法访问网络。");
            System.out.println("错误信息: " + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 将文件上传到OSS，同时保留目录结构。
     */
    private static void uploadFileToOss(OSS ossClient, String bucketName, Path baseDir, Path file) {
        // 计算文件的相对路径
        Path relativePath = baseDir.relativize(file);
        String objectName = relativePath.toString().replace("\\", "/");
        // 创建PutObjectRequest对象并上传文件。
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, file.toFile());
        PutObjectResult result = ossClient.putObject(putObjectRequest);
        System.out.println("文件上传成功：" + objectName);
    }
}
